<template>
    <view class="type-writer-container">
        <div v-html="contentText"></div>
        <text v-show="initPosition !== contentText.length" :style="{ display: initPosition % 2 == 0 || initPosition == total ? 'hidden' : 'inline-block' }"></text>
    </view>
</template>

<script lang="ts" setup>
import { ref, watch, onMounted } from 'vue';

const props = defineProps({
  contentList: {
    type: Array,
    required: true
  },
  delaytime: {
    type: Number,
    default: 0
  },
  uid: {
    type: [String, Number]
  }
});

const contentText = ref('');
const initPosition = ref(0);
const total = ref(0);
let timer : any = null;

const emit = defineEmits();

onMounted(() => {
  initWriter(props.contentList);
});

watch(props.contentList, (newvalue) => {
  clearInterval(timer);
  timer = null;
  initWriter(newvalue);
});

function initWriter(messageList: any[]) {
  const text = messageList.join('<br>');
  total.value = text.length;
  getChatContent(text);
}

function getChatContent(text: string) {
  timer = setInterval(() => {
    initPosition.value++;
    if (initPosition.value == total.value) {
      let nowStr = text.substring(0, initPosition.value);
      contentText.value = nowStr;
      clearInterval(timer);
      emit('finish', props.uid, true);
      return;
    }

    let nowStr = text.substring(0, initPosition.value);
    contentText.value = nowStr;
  }, 10);
}

// function pause() {
//   clearInterval(timer);
//   emit('pause', props.uid, true);
// }

// function continues() {
//   initWriter(props.contentList);
// }

// function reset() {
//   initPosition.value = 0;
//   initWriter(props.contentList);
// }

</script>

<style scoped lang="scss">
.type-writer-container {
	width: 100%;
	height: auto;
}
</style>